package com.sunyard.auth.handler;

import com.sunyard.auth.common.enums.AccountStatusEnum;
import com.sunyard.auth.constants.Contants;
import com.sunyard.auth.constants.ErrorCode;
import com.sunyard.auth.controller.convert.SmAuthUserConvert;
import com.sunyard.auth.exception.AuthException;
import com.sunyard.auth.model.AuthModel;
import com.sunyard.auth.redis.RedisKeyUtils;
import com.sunyard.auth.service.bo.SmAuthUserBO;
import com.sunyard.auth.utils.RandomUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @program auth
 * @description
 * @author raoinyx@163.com
 * @create 2020-07-18 00:23
 */
@Service
public class AdminHandle {
    @Resource
    private SmAuthUserHandler smAuthUserHandler;
	@Resource
	private RedisTemplate<String, Object> redisTemplateStr;

	/**
	 * 登录
	 *
	 * @param admin
	 * @return
	 */
	public String adminLogin(SmAuthUserBO admin) {
		if (ObjectUtils.isEmpty(admin) || ObjectUtils.isEmpty(admin.getUserName()) || ObjectUtils.isEmpty(admin.getPassword())) {
			throw new AuthException(ErrorCode.USERNAME_PASSWORD);
		}
        SmAuthUserBO smAuthUserBO = smAuthUserHandler.findByName(admin.getUserName());
		if (ObjectUtils.isEmpty(smAuthUserBO)) {
			throw new AuthException(ErrorCode.ACCOUNT_IS_NULL);
		}


		if (AccountStatusEnum.DISABLE.getCode().equals(smAuthUserBO.getStatus())) {
			throw new AuthException(ErrorCode.ACCOUNT_IS_DISABLE);
		}
		if (AccountStatusEnum.LEAVE.getCode().equals(smAuthUserBO.getStatus())) {
			throw new AuthException(ErrorCode.ACCOUNT_IS_LEAVE);
		}
		if (!smAuthUserBO.getPassword().equals(admin.getPassword())) {
			throw new AuthException(ErrorCode.PASSWORD_ERROR);
		}
		//生成一个UUID
		String token = RandomUtil.getToken();
		AuthModel authModel = SmAuthUserConvert.toVO(smAuthUserBO);

		//用户ID - token
		Object accountToken = redisTemplateStr.opsForValue().get(RedisKeyUtils.getAccountKey(admin.getUserName()));
		if (accountToken != null) {
			//如果存在ID-token，则需要删除ID-token 和 token-authModel
			String tokenCache = (String) accountToken;
			redisTemplateStr.delete(RedisKeyUtils.getTokenKey(tokenCache));
			redisTemplateStr.delete(RedisKeyUtils.getAccountKey(admin.getUserName()));
		}
		redisTemplateStr.opsForValue().set(RedisKeyUtils.getAccountKey(smAuthUserBO.getUserName()), token, Contants.TOKEN_TIME, TimeUnit.HOURS);

		//token model token-authModel
		redisTemplateStr.opsForValue().set(RedisKeyUtils.getTokenKey(token), authModel, Contants.TOKEN_TIME, TimeUnit.HOURS);
		return token;
	}

	/**
	 * 退出登录
	 *
	 * @param request
	 */
	public void loginOut(HttpServletRequest request) {
		String token = request.getHeader(Contants.TOKEN_KEY);
		AuthModel auth = (AuthModel) redisTemplateStr.opsForValue().get(RedisKeyUtils.getTokenKey(token));
		if (!ObjectUtils.isEmpty(auth)) {
			//先查询用户是否存在token
			String tokenCache = (String) redisTemplateStr.opsForValue().get(RedisKeyUtils.getAccountKey(String.valueOf(auth.getUserName())));
			if (!ObjectUtils.isEmpty(tokenCache)) {
				//删除UserId缓存
				redisTemplateStr.delete(RedisKeyUtils.getAccountKey(String.valueOf(auth.getUserName())));
			}
			//删除UserId缓存
			redisTemplateStr.delete(RedisKeyUtils.getTokenKey(token));
		}
	}

}
